import moment from 'moment';

const base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
function base64decode(str:string) {
  try {
    const bc = str.replace(/=/g, '').split('');
    let cOne;
    let bOne;
    let bsOne = '';
    bc.forEach(function (item) {
      cOne = '';
      for (let z = 0, l = base64Chars.length; z < l; z++) {
        if (item === base64Chars[z]) {
          cOne = z;
          break;
        }
      }
      if (cOne === '') {
        // throw new Error('编码有误');
        return str;
      }
      bOne = Number(cOne).toString(2);
      if (bOne.length < 6) {
        bOne = '00000'.concat(bOne).slice(-6);
      }
      bsOne += bOne;
    });
    const j = Math.floor(bsOne.length / 8);
    let i;
    let ha = '';
    let hb;
    for (i = 0; i < j; i++) {
      hb = parseInt(bsOne.slice(i * 8, i * 8 + 8), 2).toString(16);
      if (hb.length < 2) {
        hb = '00'.concat(hb).slice(-2);
      }
      ha += '%'.concat(hb);
    }
    return decodeURIComponent(ha);
  } catch (e) {
    return str;
  }
}
;
const notificationSetting = {
  classMap: {
    success: 'notification-succ',
    info: 'notification-run',
    error: 'notification-error',
    warn: 'notification-warn',
    done: 'notification-run'
  }
};
type NotificationType = keyof typeof notificationSetting.classMap;

export function getNotificationClass(status: NotificationType) {
  return notificationSetting.classMap[status];
}

// 添加监听插件message映射信息
export function setNotificationEvent(eventBody:any, ticket:string) {
  const storeInfo = localStorage.getItem('notification_event');
  const eventlist = storeInfo ? JSON.parse(storeInfo) || {} : {};
  eventlist[ticket] = Object.assign({ overtime: new Date().getTime() + 1 * 60 * 60 * 1000 }, eventBody);
  localStorage.setItem('notification_event', JSON.stringify(eventlist));
}

// 移除超时的映射信息
export function removeOverTimeEvent(ticket:string) {
  const storeInfo = localStorage.getItem('notification_event');
  const eventlist = storeInfo ? JSON.parse(storeInfo) || {} : {};
  delete eventlist[ticket];
  for (const name in eventlist) {
    if (eventlist[name].overtime < new Date().getTime()) {
      delete eventlist[name];
    }
  }
  localStorage.setItem('notification_event', JSON.stringify(eventlist));
}

function getOutPutTitle(data:any, body:any) {
  let temp = '';
  switch (body.operation) {
    case 'createUserContract':
      temp += '部署';
      break;
    case 'invokeUserContract':
      temp += '执行';
      break;
    default:
  }
  if (data.status === 'done') {
    temp += '结果';
  }
  temp += ' [' + body.contractName + (body.method ? ' ' + body.method : '') + '] ';
  // timestamp插件返回单位是秒
  temp += data.timestamp ? moment.unix(data.timestamp).format('yyyy-MM-DD hh:mm:ss') : '';
  // temp += data.detail;
  if (data.status === 'done') {
    switch (body.operation) {
      case 'createUserContract':
        temp += '创建合约成功';
        break;
      case 'invokeUserContract':
        temp += '合约调用成功';
        if (data.chainNodeResult && data.chainNodeResult.contractResult) {
          if (data.chainNodeResult.contractResult.contractEventList && data.chainNodeResult.contractResult.contractEventList[0]) {
            temp += ', 交易ID:';
            temp += data.chainNodeResult.contractResult.contractEventList[0].txId;
          }
          if (data.chainNodeResult.contractResult.result) {
            temp += ', 合约执行结果:';
            temp += base64decode(data.chainNodeResult.contractResult.result);
          }
        }
        break;
      default:
    }
  } else {
    temp += data.detail;
  }
  return temp;
}
export function showNotificationEvent(event:any) {
  if (!event.data) {
    return;
  }
  const data = event.data;
  const storeInfo = localStorage.getItem('notification_event');
  const eventlist = storeInfo ? JSON.parse(storeInfo) || {} : {};
  const body = eventlist[event.ticket];
  if (!body) {
    return;
  }
  let temp = '<span class="' + getNotificationClass(data.status) + '">';
  temp += getOutPutTitle(data, body);
  temp += '</span>';
  if (data.status === 'done') {
    removeOverTimeEvent(event.ticket);
  }
  return temp;
}
export const addMessageListener = (output:(param:any)=>void) => {
  window.addEventListener('message', function (event) {
    if (event.source !== window) {
      return;
    }
    const messageOutput = showNotificationEvent(event.data);
    // console.log(messageOutput);
    output(messageOutput);
  }, false);
};

// console.log("Page script received: " + event.data)
// console.log(event.data);
// const $$message = (function () {
//   const message = $('<div style="width:260px; display:none; opcity:0.8; position:fixed;bottom:0;right:0; padding:10px 10px 0px 10px;background:#595c76;font-size:14px; color:white;"></div>');
//   $('body').append(message);
//   return function (msg: any) {
//     let template = '<div style="background:#222336; margin-bottom:10px;">';
//     template += '<div style="background:#3d3f53; padding:6px; font-weight:bold; display:flex;"><div style="flex:1;">' + msg.title + '</div>';
//     template += '<div class="close-bt" style="width:40px; background:url(/chainmaker_ide/static/images/close_icon.png) no-repeat center;"></div>';
//     template += '</div>';
//     template += '<div style="padding:6px;">' + msg.message + '</div>';
//     template += '</div>';
//     const msgbox = $(template);
//     message.append(msgbox);
//     function rm() {
//       msgbox.remove();
//       if (message.html() === '') {
//         message.hide();
//       }
//     }
//     $(msgbox).find('.close-bt').click(function () {
//       rm();
//     });
//     setTimeout(function () {
//       rm();
//     }, msg.during || 3000);
//     message.show();
//   };
// })();
